package cn.itcast.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.constant.StatusConstant;
import cn.itcast.exception.DeletionNotAllowedException;
import cn.itcast.exception.SetmealEnableFailedException;
import cn.itcast.mapper.DishMapper;
import cn.itcast.mapper.SetmealDishMapper;
import cn.itcast.mapper.SetmealMapper;
import cn.itcast.result.PageBean;
import cn.itcast.service.SetmealService;
import cn.itcast.utils.AliTextModerationUtil;
import cn.itheima.goods.dto.SetmealDTO;
import cn.itheima.goods.dto.SetmealPageQueryDTO;
import cn.itheima.goods.pojo.Dish;
import cn.itheima.goods.pojo.Setmeal;
import cn.itheima.goods.pojo.SetmealDish;
import cn.itheima.goods.vo.SetmealDishVO;
import cn.itheima.goods.vo.SetmealOverViewVO;
import cn.itheima.goods.vo.SetmealVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@AllArgsConstructor
public class SetmealServiceImpl implements SetmealService {

    private SetmealMapper setmealMapper;
    private SetmealDishMapper setmealDishMapper;
    private DishMapper dishMapper;
    private AliTextModerationUtil aliTextModerationUtil;

    /**
     * 添加套餐信息
     *
     * @param setmealDTO 套餐信息
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = RedisConstant.SETMEAL_LIST, key = "#setmealDTO.categoryId")
    public void addWithDish(SetmealDTO setmealDTO) {
        //判断描述是否合法
        //textModeration(setmealDTO);

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //向套餐表插入1条数据
        setmealMapper.insert(setmeal);

        //获取insert语句生成的主键值
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            setmealDishes.forEach(x -> x.setSetmealId(setmealId));
            //向套餐表插入n条数据
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 套餐分页查询
     *
     * @param setmealPageQueryDTO 分页条件
     * @return 套餐列表
     */
    @Override
    public PageBean pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 套餐批量删除
     *
     * @param ids 套餐id集合
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = RedisConstant.SETMEAL_LIST, allEntries = true)
    public void deleteBatch(List<Long> ids) {

        List<Setmeal> setmeals = setmealMapper.getOnSaleByIds(ids);

        if (!setmeals.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        //删除套餐数据
        setmealMapper.deleteByIds(ids);
        //删除套餐关联的菜品信息
        setmealDishMapper.deleteBySetmealIds(ids);
    }

    /**
     * 根据id查询套餐详情
     *
     * @param id 要查询的套餐id
     * @return 套餐信息
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        //根据id查询菜品数据
        return setmealMapper.getById(id);
    }

    /**
     * 更新套餐信息
     *
     * @param setmealDTO 套餐信息
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = RedisConstant.SETMEAL_LIST, allEntries = true)
    public void updateWithDish(SetmealDTO setmealDTO) {
        //判断描述是否合法
        //textModeration(setmealDTO);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //修改套餐表基本信息
        setmealMapper.update(setmeal);

        //删除原有的菜品数据
        setmealDishMapper.deleteBySetmealId(setmealDTO.getId());

        //重新插入菜品数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            setmealDishes.forEach(sd -> {
                sd.setSetmealId(setmealDTO.getId());
            });
            //向套餐菜品表插入n条数据
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /*private void textModeration(SetmealDTO setmealDTO) {
        TextModerationResponseBody.TextModerationResponseBodyData textModerationResponseBodyData = aliTextModerationUtil.TextModeration(setmealDTO.getDescription());

        if (!textModerationResponseBodyData.getReason().isEmpty()) {
            TextModerationReason textModerationReason = JSON.parseObject(textModerationResponseBodyData.getReason(), TextModerationReason.class);

            throw new BaseException("涉及到非法关键字:" + textModerationReason.getRiskWords());
        }
    }*/

    /**
     * 套餐起售、停售
     *
     * @param status 状态
     * @param id     套餐id
     */
    @Override
    public void updateStatus(Integer status, Long id) {

        if (Objects.equals(status, StatusConstant.ENABLE)) {
            //查询包含的菜品是否都起售了
            List<Dish> dish = dishMapper.getNotSaleListBySetmealId(id);

            if (!dish.isEmpty()) {
                throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }

        setmealMapper.updateStatus(status, id);
    }

    /**
     * 根据分类id查询套餐列表
     *
     * @param setmeal 查询条件
     * @return 套餐列表
     */
    @Override
    @Cacheable(cacheNames = RedisConstant.SETMEAL_LIST, key = "#setmeal.categoryId",unless = "#result.size()<=0")
    public List<Setmeal> getListByCategoryId(Setmeal setmeal) {
        return setmealMapper.getListByCategoryId(setmeal);
    }

    /**
     * 根据套餐id查询菜品信息
     *
     * @param id 套餐id
     * @return 菜品列表
     */
    @Override
    public List<SetmealDishVO> getDishesById(Long id) {
        return setmealDishMapper.getDishesBySetmealId(id);
    }

    @Override
    public SetmealOverViewVO getCountByStatus() {
        return setmealMapper.getCountByStatus();
    }
}
